package com.zaizai.zaizai_good.controller;

import com.zaizai.zaizai_good.domain.R;
import com.zaizai.zaizai_good.domain.dto.UserDto;
import com.zaizai.zaizai_good.domain.pojo.User;
import com.zaizai.zaizai_good.service.UserService;
import com.zaizai.zaizai_good.utils.BaseContext;
import com.zaizai.zaizai_good.utils.JwtUtil;
import com.zaizai.zaizai_good.utils.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;

    //注册
    @PostMapping("/register")
    public R<Integer> register(@RequestBody UserDto userDto) {
        Integer result = userService.register(userDto);
        //返回注册结果
        if (result == 1) {
            return R.ok();
        } else if (result == -1) {
            return R.fail("密码不一致");
        } else {
            return R.fail("用户名已经存在");
        }
    }

    //登录
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto) {
        User user = userService.login(userDto);
        //返回登录结果
        if (user != null) {
            //判断是否有效
            if (user.getIsvalid().equals("N")) {
                return R.fail("账号已禁用");
            }
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.createJWT("zaizai", 720000000L, claims);
            //设置token
            return R.ok(token);
        } else {
            return R.fail("账号或密码错误");
        }
    }

    /**
     * 查询人员列表
     */
    @GetMapping("/list")
    public TableDataInfo list(User user) {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }
    /**
     * 查询当前登录用户信息
     */
    @GetMapping("/info")
    public R<User> getInfo() {
        return R.ok(userService.selectUserById(BaseContext.getCurrentId()));
    }
    /**
     * 获取人员详细信息
     */
    @GetMapping(value = "/{id}")
    public R<User> getInfo(@PathVariable("id") Long id) {
        return R.ok(userService.selectUserById(id));
    }

    /**
     * 新增人员
     */
    @PostMapping
    public R<Integer> add(@RequestBody User user) {
        return R.ok(userService.insertUser(user));
    }

    /**
     * 修改人员
     */
    @PutMapping
    public R<Integer> edit(@RequestBody User user) {
        return R.ok(userService.updateUser(user));
    }

    /**
     * 删除人员
     */
    @DeleteMapping("/{ids}")
    public R<Integer> remove(@PathVariable Long[] ids) {
        return R.ok(userService.deleteUserByIds(ids));
    }
}
